import { Checkbox } from 'antd'
import AutoSizer from 'react-virtualized-auto-sizer'
import { FixedSizeList } from 'react-window'
import GroupItem from '@/desktop/components/GroupItem'
import type { BaseGroup } from '@/services/contact-types/groups'
import type { QywxMap } from './hooks'

interface ListData {
  groups: BaseGroup[]
  qywxMap: QywxMap
  isChoosable: (group: BaseGroup) => boolean
  choosed: string[]
  switchChoose: (id: string) => void
}

function getItemKey(index: number, data: ListData) {
  return data.groups[index]!.id
}

function renderItem({ data, index, style }: { data: ListData; index: number; style: unknown }) {
  const group = data.groups[index]!
  const choosable = data.isChoosable(group)
  const choosed = data.choosed.includes(group.id)
  const onClick = () => data.switchChoose(group.id)

  return <div className="qun-choose-groups-choose-item-wrap" style={style as React.CSSProperties}>
    <Checkbox disabled={!choosable} checked={choosed} onClick={onClick}>
      <GroupItem contact={group} qywx={data.qywxMap.get(group.ownerWxid)} />
    </Checkbox>
  </div>
}

function renderListWithData({
  width,
  height,
  data,
}: {
  width: number
  height: number
  data: ListData
}) {
  const itemSize = 60
  return <FixedSizeList
    height={height}
    width={width}
    itemCount={data.groups.length}
    itemSize={itemSize}
    itemData={data}
    itemKey={getItemKey}
  >
    {renderItem}
  </FixedSizeList>
}

export default function GroupList(props: { data: ListData }) {
  const { data: listData } = props
  const renderList = useCallback(
    (base: { width: number; height: number }) => renderListWithData({ ...base, data: listData }),
    [listData],
  )
  return <AutoSizer>{renderList}</AutoSizer>
}
